package prj.carmap.mobile.process;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.MainActivity;
import prj.carmap.mobile.activity.SellerActivity;
import prj.carmap.mobile.model.SellerInfo;
import prj.carmap.mobile.util.BMapUtil;
import prj.carmap.mobile.util.ColorUtil;
import prj.carmap.mobile.util.ImageLoader;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 位置变化处理器 处理位置变化时商家和广告信息的更新
 * 
 */
@SuppressLint("NewApi")
public class MyLocationProcess extends AsyncHttpResponseHandler {

	private static AsyncHttpClient client = new AsyncHttpClient();

	private Context context;
	private MapView mapView = null;
	private GridView gridView = null;
	SellerOverlay mOverlay = null;
	List<TextOverlay> textOverlays = new ArrayList<TextOverlay>();
	boolean isInit = false;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;
	private Button button = null;
	private OverlayItem mCurItem = null;

	private View popupInfo = null;

	/** 地图信息获取中 */
	boolean in_mapinfo = false;

	MainActivity mainActivity;

	public MyLocationProcess(MainActivity mainActivity) {
		this.mainActivity = mainActivity;
	}

	/**
	 * 位置变化时，重置文本信息
	 */
	public void resetTextOverlay() {
		if (mOverlay == null)
			return;

		for (TextOverlay textOverlay : textOverlays) {
			mapView.getOverlays().remove(textOverlay);
		}

		/*
		 * for (OverlayItem item : (List<OverlayItem>) mOverlay.getAllItem()) {
		 * TextOverlay textOverlay = createTextOverlay(item.getTitle(),
		 * item.getPoint()); mapView.getOverlays().add(textOverlay);
		 * textOverlays.add(textOverlay); }
		 */

		mapView.refresh();
	}

	/**
	 * 位置变化时，重新请求服务器端商家和广告信息
	 */
	public void refreshMap(double lng, double lat) {
		if (!in_mapinfo) {
			in_mapinfo = true;

			Log.i("sss refreshMap", CarmapApplication.SERVER_URL
					+ "/rest/mapinfo/" + lng + "/" + lat);
			client.get(CarmapApplication.SERVER_URL + "/rest/mapinfo/" + lng
					+ "/" + lat, this);
			// client.get(CarmapApplication.SERVER_URL + "/rest/advert/" +
			// 105.979973 + "/" + 31.584996, new AdvertUpdateListener());
			client.get(CarmapApplication.SERVER_URL + "/rest/advert/" + lng
					+ "/" + lat, new AdvertUpdateListener());

		}
	}

	/**
	 * 获得服务器全部数据
	 */
	public void getAllMapData() {
		// http://115.28.233.56/carmap/rest/seller/all
		client.get(CarmapApplication.SERVER_URL + "/rest/seller/bytype/24", this);
	}

	/**
	 * 商家信息返回时更新地图marker
	 * 
	 * @param content
	 *            the body of the HTTP response from the server
	 * @throws JSONException
	 */
	public void onSuccess(String content) {
		Log.i("sss", "seller:" + content);
		try {
			JSONArray jsonAry = new JSONArray(content);
			if (jsonAry != null && jsonAry.length() > 0) {
				initOverlay(jsonAry);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		/*
		 * try { JSONArray jsonAry = new JSONArray(content);
		 * initOverlay(jsonAry);
		 * 
		 * in_mapinfo = false; } catch (JSONException e) { e.printStackTrace();
		 * }
		 */
	}

	/**
	 * 取得商家信息失败时处理
	 * 
	 * @param error
	 *            the underlying cause of the failure
	 * @param content
	 *            the response body, if any
	 */
	public void onFailure(Throwable error, String content) {
		in_mapinfo = false;
	}

	/**
	 * 更新地图
	 * 
	 * @param sellers
	 */
	private void initOverlay(JSONArray sellers) {
		if (isInit)
			return;

		// isInit = true;
		if (mOverlay != null) {
			if (mapView != null) {
				mapView.getOverlays().remove(mOverlay);
				for (TextOverlay textOverlay : textOverlays) {
					mapView.getOverlays().remove(textOverlay);
				}
				textOverlays.clear();
			}
			mOverlay.removeAll();
		}

		mOverlay = new SellerOverlay(context.getResources().getDrawable(
				R.drawable.icon_marka_red), mapView);
		// 将overlay 添加至MapView中

		// 创建自定义overlay

		// 准备overlay 数据
		for (int i = 0; i < sellers.length(); i++) {
			// TODO 一次加载太多，会把前端拖死，目前是控制数量了
			// 建议是前端缓存数据，增加按钮例如“上一组”，“下一组”来在地图上翻页显示，即一次只显示可控数量的点
			/*
			 * if (i > 30) { break; }
			 */

			try {
				JSONObject seller = (JSONObject) sellers.get(i);
				GeoPoint p1 = new GeoPoint(
						(int) (seller.getDouble("latitude") * 1E6),
						(int) (seller.getDouble("longitude") * 1E6));
				if (seller.getString("sellerName") != null
						&& seller.getString("superSellerType") != null) {
					String title = seller.getString("sellerName") + ";"
							+ seller.getString("superSellerType");
					OverlayItem item1 = new OverlayItem(p1, title,
							seller.getString("sellerId"));
					if (seller.getString("superSellerType").equals("21")) {
						item1.setMarker(context.getResources().getDrawable(
								R.drawable.icon_marka_red));
					} else if (seller.getString("superSellerType").equals("27")) {
						item1.setMarker(context.getResources().getDrawable(
								R.drawable.icon_marka_blue));
					}
					mOverlay.addItem(item1);
				}
				// TODO 当地图足够大时，显示文字标签
				// TextOverlay textOverlay =
				// createTextOverlay(seller.getString("sellerName"), p1);
				// mapView.getOverlays().add(textOverlay);
				// textOverlays.add(textOverlay);
			} catch (Exception ex) {
			}
		}
		mapView.getOverlays().add(mOverlay);
		// 刷新地图
		mapView.refresh();

		/**
		 * 向地图添加自定义View.
		 */
		LayoutInflater mInflater = LayoutInflater.from(context);
		viewCache = mInflater.inflate(R.layout.custom_text_view, null);
		popupInfo = (View) viewCache.findViewById(R.id.popinfo);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);

		button = new Button(context);
		button.setBackgroundResource(R.drawable.popup);

		/**
		 * 创建一个popupoverlay
		 */
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				client.get(CarmapApplication.SERVER_URL + "/rest/seller/"
						+ mCurItem.getSnippet(),
						new AsyncHttpResponseHandler() {
							public void onSuccess(String content) {
								try {
									JSONObject json = new JSONObject(content);
									Intent intent = new Intent(context,
											SellerActivity.class);
									intent.putExtra("currentSeller",
											SellerInfo.fromJson(json));
									context.startActivity(intent);
									pop.hidePop();
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							public void onFailure(Throwable error,
									String content) {
								pop.hidePop();
							}
						});
			}
		};
		pop = new PopupOverlay(mapView, popListener);
	}

	public MapView getMapView() {
		return mapView;
	}

	public void setMapView(MapView mapView) {
		this.mapView = mapView;
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public GridView getGridView() {
		return gridView;
	}

	public void setGridView(GridView gridView) {
		this.gridView = gridView;
	}

	/**
	 * 地图上商家表示Overlay对象
	 * 
	 * @author wangs
	 * 
	 */
	public class SellerOverlay extends ItemizedOverlay<OverlayItem> {

		public SellerOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}

		/**
		 * 点击marker时迁移到详细信息画面
		 */
		@Override
		public boolean onTap(int index) {
			OverlayItem item = getItem(index);
			mCurItem = item;
			popupText.setText(getItem(index).getTitle().split(";")[0]);
			if (getItem(index).getTitle().split(";")[1].equals("21")) {
				popupText.setBackground(context.getResources().getDrawable(
						R.drawable.popup_middle_red));
			} else if (getItem(index).getTitle().split(";")[1].equals("27")) {
				popupText.setBackground(context.getResources().getDrawable(
						R.drawable.popup_middle));
			}
			Bitmap[] bitMaps = { BMapUtil.getBitmapFromView(popupInfo), };
			pop.showPopup(bitMaps, item.getPoint(), 32);

			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			if (pop != null){
                pop.hidePop();
                mMapView.removeView(button);
			}
			return false;
		}
	}

	/**
	 * 由于百度api2。0之后不支持ItemizedOverlay自定义绘制， 使用TextOverlay配合marker展示商家名字
	 * 
	 * @param title
	 * @param pos
	 * @return
	 */
	/*
	 * public TextOverlay createTextOverlay(String title, GeoPoint pos) {
	 * Projection projection = mapView.getProjection(); Point point =
	 * projection.toPixels(pos, null); point.y = point.y - 65;
	 * 
	 * Symbol textSymbol = new Symbol(); Symbol.Color textColor = textSymbol.new
	 * Color(); textColor.alpha = 255; textColor.red = 53; textColor.blue = 43;
	 * textColor.green = 16;
	 * 
	 * Symbol textSymbol1 = new Symbol(); Symbol.Color textColor1 =
	 * textSymbol1.new Color(); textColor1.alpha = 230; textColor1.red = 219;
	 * textColor1.blue = 44; textColor1.green = 179;
	 * 
	 * TextItem textItem = new TextItem(); textItem.fontColor = textColor;
	 * textItem.bgColor = textColor1; textItem.fontSize = 28; textItem.text =
	 * title; textItem.pt = projection.fromPixels(point.x, point.y);
	 * 
	 * TextOverlay textOverlay = new TextOverlay(mapView);
	 * textOverlay.addText(textItem); return textOverlay; }
	 */

	/**
	 * 广告更新处理类
	 * 
	 * @author wangs
	 * 
	 */
	class AdvertUpdateListener extends AsyncHttpResponseHandler {
		/**
		 * 取得广告信息成功
		 * 
		 * @param content
		 *            the body of the HTTP response from the server
		 * @throws JSONException
		 */
		public void onSuccess(String content) {
			Log.i("sss", "Advert:" + content);
			try {
				JSONArray jsonAry = new JSONArray(content);
				MyLocationProcess.this.gridView.setAdapter(new AdvertAdapter(
						jsonAry, MyLocationProcess.this.context,
						MyLocationProcess.this.gridView, 2, 4));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

}

/**
 * 自定义适配器，用来展示广告图标
 * 
 * @author wangs
 * 
 */
class AdvertAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private JSONArray adverts;
	private Context context;
	private GridView gridView;
	private int cols;
	private int total = 0;

	public AdvertAdapter(JSONArray jsonAry, Context context, GridView gridView,
			int COLS, int total) {
		super();

		JSONArray tempAry = new JSONArray();
		for (int i = 0; i < 4 - jsonAry.length(); i++) {
			tempAry.put(new JSONObject());
		}
		for (int i = 0; i < jsonAry.length(); i++) {
			try {
				tempAry.put(jsonAry.get(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		gridView.setHorizontalSpacing(0);
		gridView.setVerticalSpacing(0);
		this.adverts = tempAry;
		this.context = context;
		this.gridView = gridView;
		this.cols = COLS;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return 4;
	}

	@Override
	public Object getItem(int position) {
		try {
			if (position < adverts.length()) {
				return adverts.getJSONObject(position);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return new JSONObject();
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		JSONObject json;
		try {
			json = adverts.getJSONObject(position);
			if (!json.has("advertTitle")) {
				ViewHolder viewHolder;

				convertView = inflater.inflate(R.layout.advert_view_text, null);
				viewHolder = new ViewHolder();
				viewHolder.title = (TextView) convertView;
				viewHolder.title.setTextColor(ColorUtil.colorStr2Int("cdcdcd"));
				viewHolder.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
				// viewHolder.image.setImageResource(R.drawable.empty_advert);
				// //viewHolder.image.setScaleType(ScaleType.FIT_XY);
				return convertView;
			}
			// String picPath = json.getString("advertPic");
			// Log.i("sss", picPath);
			String advertTitle = json.getString("advertTitle");
			String color = json.getString("advertColor");
			// if (picPath != null && !picPath.equals("") &&
			// !picPath.equals("null"))
			// {
			// ViewHolder viewHolder;
			// convertView = inflater.inflate(R.layout.advert_view_image, null);
			// viewHolder = new ViewHolder();
			// viewHolder.image = (ImageView) convertView;
			// String picUrl = picPath;
			// //viewHolder.image.setScaleType(ScaleType.FIT_XY);
			// ImageLoader imageLoader = new ImageLoader();
			// imageLoader.showImageAsyn(viewHolder.image,
			// CarmapApplication.SERVER_URL + "/images/" + picUrl,
			// R.drawable.empty_advert);
			// }
			if (advertTitle != null && !"".equals(advertTitle)) {
				ViewHolder viewHolder;
				convertView = inflater.inflate(R.layout.advert_view_text, null);
				viewHolder = new ViewHolder();
				viewHolder.title = (TextView) convertView;
				viewHolder.title.setTextColor(ColorUtil.colorStr2Int("000000"));
				viewHolder.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
				viewHolder.title.setText(advertTitle);
			} else {
				ViewHolder viewHolder;

				convertView = inflater.inflate(R.layout.advert_view_text, null);
				viewHolder = new ViewHolder();
				viewHolder.title = (TextView) convertView;
				viewHolder.title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);
				// viewHolder.image.setScaleType(ScaleType.FIT_XY);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();

		// float density = dm.density; // 屏幕密度（像素比例：0.75/1.0/1.5/2.0）
		// AbsListView.LayoutParams params = new AbsListView.LayoutParams(
		// (int) ((wm.getDefaultDisplay().getWidth() - 14 * density) / 2),
		// (gridView.getHeight() - (int) density * 5) / 2);
		// convertView.setLayoutParams(params);
		return convertView;
	}
}

class ViewHolder {
	public TextView title;
	public ImageView image;
}
